package com.kgc.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kgc.annotation.CheckPermission;
import com.kgc.entity.User;
import com.kgc.service.UserService;
import com.kgc.service.impl.EmailService;
import com.kgc.util.RandomNumberUtil;
import com.kgc.util.ResultAjax;
import com.kgc.util.SM3Util;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author :qinya
 * @PackageName:com.kgc.controller
 * @ClassName: UserController
 * @Description: TODO
 * @date : 2025/5/15,0:27
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EmailService emailService;
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/page")
    @CheckPermission("1")
    public ResultAjax queryByPage(@RequestParam Map<String, String> params) throws ParseException {
        Map<String, Object> map = new HashMap<>();
        logger.debug("时间" + params.get("startDate"));
        if (!StringUtils.isEmpty(params.get("searchUserName"))) {
            map.put("searchUserName", '%' + params.get("searchUserName") + '%');
        }
        if (!StringUtils.isEmpty(params.get("startDate"))) {
            map.put("startDate", params.get("startDate"));
            logger.debug("起始日期" + map.get("startDate"));
        }
        if (!StringUtils.isEmpty(params.get("endDate"))) {
            map.put("endDate", params.get("endDate"));
            logger.debug("截止日期" + map.get("endDate"));
        }
        map.put("pageNum", Integer.parseInt(params.get("pageNum")));
        map.put("pageSize", Integer.parseInt(params.get("pageSize")));
        return ResultAjax.success().add("pageInfo", userService.selectUserByPage(map));
    }

    @PostMapping("/login")
    public ResultAjax login(@RequestBody User user) throws JsonProcessingException {
        //使用SM3算法给输入的密码进行加密
        String encryptionPwd = SM3Util.hash(user.getPassword());
        Map<String, Object> map = userService.userLogin(user.getLoginName(), encryptionPwd);
        System.out.println("JSON字符串" + new ObjectMapper().writeValueAsString(map.get("user")));
        return ResultAjax.success()
                .add("token", map.get("jwt").toString())
                .add("user", new ObjectMapper().writeValueAsString(map.get("user")));
    }

    @PostMapping("/register")
    public ResultAjax addUser(@RequestBody User user) {
        user.setCreateDate(new Date());
        user.setPassword(SM3Util.hash(user.getPassword()));
        return ResultAjax.success().add("addStatus", userService.addUser(user));
    }

    @PostMapping("/edit")
    @CheckPermission("1")
    public ResultAjax editUser(@RequestBody User user) {
        System.out.println(user);
        return ResultAjax.success().add("editStatus", userService.editUserByManager(user));
    }

    @CheckPermission({"1", "0"})
    @GetMapping("/find/{id}")
    public ResultAjax findUser(@PathVariable("id") int id) {
        return ResultAjax.success().add("User", userService.selectUserById(id));
    }

    @GetMapping("/del/{id}")
    @CheckPermission("1")
    public ResultAjax delUser(@PathVariable("id") int id) {
        return ResultAjax.success().add("delStatus", userService.deleUser(id));
    }

    @GetMapping("/checkEmail")
    public ResultAjax checkEmail(String email) {
        return ResultAjax.success().add("checkStatus", userService.checkEmail(email));
    }

    @GetMapping("/checkLoginName")
    public ResultAjax checkLoginName(String loginName) {
        return ResultAjax.success().add("checkStatus", userService.checkLoginName(loginName));
    }

    @GetMapping("/sendEmailCode")
    public ResultAjax sendEmailCode(String email) {
        String authCode = RandomNumberUtil.getRandomNumber();
        redisTemplate.opsForValue().set(email, authCode, 5, TimeUnit.MINUTES);
        emailService.sendSimpleMail(email, "注册邮箱验证码", authCode);
        return ResultAjax.success().add("sendStatus", true);
    }

    @GetMapping("/verifyEmailCode")
    public ResultAjax verifyEmailCode(String email, String emailCode) {
        Object authCode = redisTemplate.opsForValue().get(email);
        if (authCode == null || !emailCode.equals(authCode.toString())) {
            return ResultAjax.success().add("verifyStatus", false);
        }
        return ResultAjax.success().add("verifyStatus", true);
    }


    @RequestMapping("/checkOldPassword")
    public ResultAjax checkOldPassword(@RequestBody Map<String, String> params) {
        int id = Integer.parseInt(params.get("id"));
        String oldPassword = params.get("oldPassword");
        if (userService.selectUserById(id).getPassword().equals(SM3Util.hash(oldPassword))) {
            return ResultAjax.success().add("result", "true");
        }
        return ResultAjax.success().add("result", "false");
    }


    @RequestMapping("/updatePassword")
    public ResultAjax updatePassword(@RequestBody Map<String, String> params) {
        int id = Integer.parseInt(params.get("id"));
        String password = params.get("password");
        if (userService.updateUserPassword(id, SM3Util.hash(password)) > 0) {
            System.out.println("执行成");
            return ResultAjax.success().add("result", "修改成功");
        }
        System.out.println("执行失败");
        return ResultAjax.success().add("result", "修改失败");
    }


}
